package com.yh.csx.event.order;

import com.yh.csx.bsf.cat.method.CatMethod;
import com.yh.csx.event.client.event.EventBusUtils;
import com.yh.csx.event.client.event.EventMessage;
import com.yh.csx.event.client.event.EventMessageBuilder;
import com.yh.csx.event.client.event.EventMessageUtils;
import com.yh.csx.event.common.id.IdGenerator;
import com.yh.csx.event.common.utils.ValueUtils;
import com.yh.csx.event.domain.order.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.eventmesh.client.tcp.impl.LoadBalanceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangsheng
 * @date 2021/8/27 14:35
 */
@Slf4j
@Service
public class OrderService {
    private List<String> ids = new ArrayList<>();
    private String topic = "event_test";
    @Autowired
    private LoadBalanceContext loadBalanceContext;

    @CatMethod("event")
    public boolean publishOrder(String topic, int num) {
        long all = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            Order order = ValueUtils.values(new Order());
            order.setBizId(IdGenerator.uuid());
            order.setOrderId("id_" + i);
            order.setEventType("orderCreated");
            EventMessage<Order> eventMessage = EventMessageBuilder.<Order>builder()
                    .bizId(order.getBizId())
                    .eventType(order.getEventType())
                    .bizType(order.getEventType())
                    .topic(topic)
                    .locationCode("W503")
                    .payLoad(order)
                    .creator("test")
                    .build();
            try {
                long start = System.currentTimeMillis();
                EventBusUtils.publishEvent(eventMessage);
//                loadBalanceContext.getDefaultPub().publish(EventMessageUtils.createPubEvent(eventMessage), 20000);
                log.info("<=publish=>topic:{} , bizId:{} ,spend:{} milliseconds.", topic, order.getBizId(),
                        (System.currentTimeMillis() - start) );
            } catch (Exception e) {
                log.error("publish test : ", e);
            }
        }
        log.info("<=publish=>topic:{} ,spend:{} milliseconds.", topic, (System.currentTimeMillis() - all));
        return true;
    }

}
